package com.gitee.l0km.xthrift.service;

import java.util.ArrayList;
import java.util.List;

import com.facebook.nifty.core.RequestContext;
import com.facebook.swift.service.ThriftEventHandler;
/**
 * copy from {@link com.facebook.swift.service.ContextChain}(org.apache.thrift:libthrift:0.12.0)<br>
 * @author guyadong
 *
 */
public class XThriftContextChain
{
    private final List<ThriftEventHandler> handlers;
    private final String methodName;
    private final List<Object> contexts;

    XThriftContextChain(List<ThriftEventHandler> handlers, String methodName, RequestContext requestContext)
    {
        this.handlers = handlers;
        this.methodName = methodName;
        this.contexts = new ArrayList<>();
        for (ThriftEventHandler h: this.handlers) {
            this.contexts.add(h.getContext(methodName, requestContext));
        }
    }

    public void preRead()
    {
        for (int i = 0; i < handlers.size(); i++) {
            handlers.get(i).preRead(contexts.get(i), methodName);
        }
    }

    public void postRead(Object[] args)
    {
        for (int i = 0; i < handlers.size(); i++) {
            handlers.get(i).postRead(contexts.get(i), methodName, args);
        }
    }

    public void preWrite(Object result)
    {
        for (int i = 0; i < handlers.size(); i++) {
            handlers.get(i).preWrite(contexts.get(i), methodName, result);
        }
    }

    public void preWriteException(Throwable t)
    {
        for (int i = 0; i < handlers.size(); i++) {
            handlers.get(i).preWriteException(contexts.get(i), methodName, t);
        }
    }

    public void postWrite(Object result)
    {
        for (int i = 0; i < handlers.size(); i++) {
            handlers.get(i).postWrite(contexts.get(i), methodName, result);
        }
    }

    public void postWriteException(Throwable t)
    {
        for (int i = 0; i < handlers.size(); i++) {
            handlers.get(i).postWriteException(contexts.get(i), methodName, t);
        }
    }

    public void done()
    {
        for (int i = 0; i < handlers.size(); i++) {
            handlers.get(i).done(contexts.get(i), methodName);
        }
    }
}
